package com.doucome.snapshot.view
{
	import com.adobe.images.JPGEncoder;
	import com.adobe.serialization.json.JSON;
	import com.doucome.snapshot.Global;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import flash.net.*;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.utils.ByteArray;
	
	/**
	 * ...
	 * @author wkl
	 */
	public class Photo extends Sprite
	{
		private var _photo_view:MovieClip;
		private var _photo_toolbar_view:MovieClip;
		private var bitMap:Bitmap;
		private var photoBmd:BitmapData;
		private var photo_w:int = 210;
		private var photo_h:int = 280;
		//private var _txt_msg:TextField;
		private var _txt_info:TextField;
		private var _txt_headimg:TextField;
		private var _photoid:int = 0;
		private var _photono:String = "";
		private var _photo_userid:int;
		//private var _wait_cube_effect:WaitCubeEffect;
		private var up_url:String;
		public static const PIC_UPLOADED_EVENT:String = "PicUpLoadedEvent";
		public static const PIC_LOADED_EVENT:String = "PicLoadedEvent";
		public static const PIC_UPLOAD_FAIL_EVENT:String = "PicUpLoadFailEvent";
		public static const PIC_LOAD_FAIL_EVENT:String = "PicLoadFailEvent";
		public static const PIC_RETAKE_EVENT:String = "PicRetakeEvent";
		private var _photourl:String;
		private var _infoView:Sprite;
		private var _infotText:String;
		private var _headimgUrl:String;
		private var _btnBB:SimpleButton;
		private var _btnLike:SimpleButton;
		private var _btnJb:SimpleButton;
		private var _type:int;
		private var _jb_effect:MovieClip;
		private var _like_effect:MovieClip;
		private var _xz:int;
		private var _btnReTake:BtnReTakePic;
		
		public function Photo(photoType:int)
		{
			_type = photoType;
			init();
		
		}
		
		public function showPic(bmd:BitmapData):void
		{
			if (bmd !== null)
			{
				var map = new Bitmap(bmd);
				
				if (!_photo_view.contains(bitMap))
				{
					
					_photo_view.addChild(bitMap);
				}
				
				this.bitMap.bitmapData = getZoomDraw(map, photo_w, photo_h, false);
				
			}
			else
			{
				return;
			}
		
		}
		
		private function init():void
		{
			_photo_view = getChildByName("photo_view") as MovieClip;
			_photo_toolbar_view = getChildByName("photo_toolbar") as MovieClip;
			_jb_effect = getChildByName("jb_effect") as MovieClip;
			_like_effect = getChildByName("like_effect") as MovieClip;
			_like_effect.visible = false;
			_jb_effect.visible = false;
			photo_w = _photo_view.width;
			photo_h = _photo_view.height;
			photoBmd = new BitmapData(photo_w, photo_h, true);
			bitMap = new Bitmap(photoBmd);
			
			if (_type == 1)
			{
				_btnJb = new BtnJb();
				_btnJb.x = 3;
				_btnJb.y = 3;
				
				_btnLike = new BtnAm();
				_btnLike.x = 179;
				_btnLike.y = 3;
				_photo_toolbar_view.addChild(_btnJb);
				
				_photo_toolbar_view.addChild(_btnLike);
				_btnJb.addEventListener(MouseEvent.CLICK, onJB);
				_btnLike.addEventListener(MouseEvent.CLICK, onLike);
			}
			else
			{
				_btnReTake = new BtnReTakePic();
				_btnReTake.x = 125;
				_btnReTake.y = 3;
				_photo_toolbar_view.addChild(_btnReTake);
				_btnReTake.addEventListener(MouseEvent.CLICK, onReTake);
			}
		}
		
		private function onReTake(e:MouseEvent):void
		{
			dispatchEvent(new Event(PIC_RETAKE_EVENT));
		
		}
		
		
		private function onLike(e:MouseEvent):void
		{
			var rq = new URLRequest("http://" + Global.APP_SERVER + "/snapshot/index.php");
			var vars:URLVariables = new URLVariables("a=like&likeid=" + _photo_userid + "&submitid=" + Global.user.id + "&photoid=" + _photoid);
			rq.data = vars;
			sendToURL(rq);
			_like_effect.visible = true;
			_like_effect.play();
			_btnLike.visible = false;
		}
		
		private function onJB(e:MouseEvent):void
		{
			var rq = new URLRequest("http://" + Global.APP_SERVER + "/snapshot/index.php");
			var vars:URLVariables = new URLVariables("a=jubao&jubaoid=" + _photo_userid + "&submitid=" + Global.user.id + "&photoid=" + _photoid);
			rq.data = vars;
			sendToURL(rq);
			_jb_effect.visible = true;
			_jb_effect.play();
			_btnJb.visible = false;
		}
		
		public function loadPic():void
		{
			
			//发送匹配图片请求
			if (_photo_view.contains(bitMap))
			{
				
				_photo_view.removeChild(bitMap);
			}
			
			var rq:URLRequest = new URLRequest("http://" + Global.APP_SERVER + "/snapshot/index.php");
			var vars:URLVariables = new URLVariables("a=show&userid=" + Global.user.id + "&gender=" + Global.user.gender);
			rq.data = vars;
			var ld:URLLoader = new URLLoader();
			ld.addEventListener(Event.OPEN, onGetPicInfoStart);
			ld.addEventListener(Event.COMPLETE, onGetPicInfoComplete);
			ld.addEventListener(ProgressEvent.PROGRESS, onGetPicInfoProgress);
			ld.addEventListener(IOErrorEvent.IO_ERROR, onGetPicInfoError);
			ld.load(rq);
		
		}
		
		private function onGetPicInfoProgress(e:ProgressEvent):void
		{
			//dispatchEvent(new Event(ProgressEvent.PROGRESS));
		}
		
		private function onGetPicInfoStart(e:Event):void
		{
			//trace("get picinfo start");
			//_txt_msg.htmlText = "<font color='#ffffff' face='Arial' size='18'>" + Local.PHTO_LOAD + "</font>";
			//dispatchEvent(new Event(Event.OPEN));
		}
		
		private function onGetPicInfoError(e:IOErrorEvent):void
		{
			//trace("get picinfo error");
			dispatchEvent(new Event(Photo.PIC_LOAD_FAIL_EVENT));
			//_txt_msg.htmlText = "<font color='#ffffff' face='Arial' size='18'>" + Local.PHTO_LOAD_ERROR + "</font>";
		}
		
		private function onGetPicInfoComplete(event:Event):void
		{
			
			//trace("picinfo loaded!");
			//解析图片信息
			
			if (null !== event.target.data)
			{
				
				var photo_info:Array = com.adobe.serialization.json.JSON.decode(event.target.data);
				_photoid = photo_info[0].photoid;
				_photourl = photo_info[0].url;
				_photo_userid = photo_info[0].userid;
				
				if (_photo_userid > 0)
				{
					//显示对方信息
					//_infotText = photo_info[0].nickname + "-" + photo_info[0].province + "-" + photo_info[0].city;
					//_headimgUrl = photo_info[0].figureurl;
					//_txt_info.htmlText = "<p><span class='info'>" + _infotText + "</span><p>";
					//_txt_headimg.htmlText = " <img src='" + _headimgUrl + "'>";
					
				}
			}
			
			//获取图片
			var ld:Loader = new Loader();
			var rq:URLRequest = new URLRequest("http://" + Global.IMG_SERVER + _photourl);
			ld.load(rq);
			ld.addEventListener(Event.OPEN, onPicLoadStart);
			ld.contentLoaderInfo.addEventListener(Event.COMPLETE, onPicLoadComplete);
			ld.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onPicLoadProgress);
			ld.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onPicLoadError);
			//
		}
		
		private function onPicLoadError(e:IOErrorEvent):void
		{
			trace("load pic error");
			//_txt_msg.htmlText = "<font color='#ffffff' face='Arial' size='18'>" + Local.PHTO_LOAD_ERROR + "</font>";
			dispatchEvent(new Event(Photo.PIC_LOAD_FAIL_EVENT));
		}
		
		private function onPicLoadStart(e:Event):void
		{
			//_wait_cube_effect.visible = true;
			//_txt_msg.htmlText = "<font color='#ffffff' face='Arial' size='18'>" + "2" + Local.PHTO_LOAD + "</font>";
			//dispatchEvent(new Event(Event.OPEN));
		}
		
		private function onPicLoadComplete(e:Event):void
		{
			
			var data:DisplayObject = e.target.content;
			var bmd:BitmapData = getZoomDraw(data, photo_w, photo_h, false);
			showPic(bmd);
			//_infoView.visible = true
			//_txt_msg.htmlText = "";
			//_wait_cube_effect.visible = false;
			_btnLike.visible = true;
			_btnJb.visible = true;
			dispatchEvent(new Event(Photo.PIC_LOADED_EVENT));
		
		}
		
		public function reset():void
		{
			if (_photo_view.contains(bitMap))
			{
				_photo_view.removeChild(bitMap);
			}
			
			if (_btnJb)
			{
				_btnJb.visible = false;
			}
			if (_btnLike)
			{
				_btnLike.visible = false;
			}
		
		}
		
		private function onPicLoadProgress(event:ProgressEvent):void
		{
			//trace("get photo");
			//var per:int = (event.bytesLoaded / event.bytesTotal) * 100;
			//_txt_msg.htmlText = "<font color='#ffffff' face='Arial' size='18'>"  + Local.PHTO_LOAD + per + "%</font>";
			dispatchEvent(new Event(ProgressEvent.PROGRESS));
		
		}
		
		/**
		 * 获取按指定尺寸等比例缩放+居中的截图
		 * @param	target        目标对象
		 * @param	tarW          目标尺寸(宽)
		 * @param	tarH          目标尺寸(高)
		 * @param	full          是否显示图片全貌
		 * @return
		 */
		private function getZoomDraw(target:DisplayObject, tarW:int, tarH:int, full:Boolean = true):BitmapData
		{
			//获取显示对象矩形范围
			var rect:Rectangle = target.getBounds(target);
			//计算出应当缩放的比例
			var perw = tarW / rect.width;
			var perh = tarH / rect.height;
			var scale = full ? ((perw <= perh) ? perw : perh) : ((perw <= perh) ? perh : perw);
			//trace("scale：" + scale);
			
			//计算缩放后与规定尺寸之间的偏移量
			var offerW = (tarW - rect.width * scale) / 2;
			var offerH = (tarH - rect.height * scale) / 2;
			//开始绘制快照（这里透明参数是false,是方便观察效果，实际应用可改为true)
			var bmd:BitmapData = new BitmapData(tarW, tarH, false, 1);
			var matrix:Matrix = new Matrix();
			matrix.scale(scale, scale);
			matrix.translate(offerW, offerH);
			bmd.draw(target, matrix);
			//如果是bitmap对象，释放位图资源
			if (target is Bitmap)
				(target as Bitmap).bitmapData.dispose();
			//返回截图数据
			return bmd;
		}
		
		public function upload():void
		{
			//_wait_cube_effect.visible = true;
			//_txt_msg.htmlText = "<font color='#ffffff' face='Arial' size='18'>" + Local.PHTO_LOAD + "</font>";
			var jpgEncoder = new JPGEncoder(80); //图片质量
			var jpgStream:ByteArray = jpgEncoder.encode(this.bitMap.bitmapData);
			//trace("appserver:" + Global.APP_SERVER);
			up_url = "http://" + Global.APP_SERVER + "/snapshot/index.php?a=savepic&userid=" + Global.user.id + "&gender=" + Global.user.gender;
			
			var jpgURLRequest:URLRequest = new URLRequest(encodeURI(up_url));
			//var vars:URLVariables = new URLVariables();
			jpgURLRequest.data = jpgStream;
			jpgURLRequest.method = URLRequestMethod.POST;
			jpgURLRequest.contentType = "application/octet-stream";
			var jpg_loader:URLLoader = new URLLoader();
			jpg_loader.dataFormat = URLLoaderDataFormat.BINARY;
			jpg_loader.addEventListener(Event.OPEN, onJpgLoaderOpen);
			jpg_loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			jpg_loader.addEventListener(Event.COMPLETE, uploadCompleteHandler);
			jpg_loader.addEventListener(ProgressEvent.PROGRESS, uploadProgressHandler);
			jpg_loader.load(jpgURLRequest);
		}
		
		private function onJpgLoaderOpen(e:Event):void
		{
			
			//_wait_cube_effect.visible = true;
			dispatchEvent(new Event(Event.OPEN));
		
		}
		
		private function uploadProgressHandler(e:ProgressEvent):void
		{
			//trace("progress:" + e.bytesLoaded);
			//dispatchEvent(new Event(ProgressEvent.PROGRESS));
		}
		
		private function uploadCompleteHandler(e:Event):void
		{
			//trace("upload finish!" + e.target.data);
			dispatchEvent(new Event(Photo.PIC_UPLOADED_EVENT));
		}
		
		private function errorHandler(e:Event):void
		{
			trace("io_error" + up_url);
			dispatchEvent(new Event(Photo.PIC_UPLOAD_FAIL_EVENT));
		}
		
		public function get photoid():int
		{
			return _photoid;
		}
		
		public function set photoid(value:int):void
		{
			_photoid = value;
		}
		
		public function get photono():String
		{
			return _photono;
		}
		
		public function set photono(value:String):void
		{
			_photono = value;
		}
		
		public function get photo_userid():int
		{
			return _photo_userid;
		}
		
		public function set photo_userid(value:int):void
		{
			_photo_userid = value;
		}
		
		public function get txt_info():TextField
		{
			return _txt_info;
		}
		
		public function set txt_info(value:TextField):void
		{
			_txt_info = value;
		}
	
	}

}